<?php
namespace App\Http\Controllers\View;

use App\Entity\Product;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use App\Entity\CartItem;

/**
 *
 */
class CartController extends Controller
{

    public function toCart(Request $request)
    {
        $cart_items = array();
        $bk_cart = $request->cookie('bk_cart');
        $bk_cart_arr = ($bk_cart !=  null ? explode(',',$bk_cart) : array());

        if($request->session()->get('member') !=''){
            $cart_items=$this->syncCart();
        }
        foreach ($bk_cart_arr as $key => $value){
            //获取冒号早字符串中的位置
            $index = strpos($value,':');
            $cart_item = new CartItem;
            $cart_item->id = $key;
            $cart_item->product_id = substr($value,0,$index);
            $cart_item->count = (int) substr($value,$index + 1);
            $cart_item->product = Product::find($cart_item->product_id);
//            return $cart_item;

            if($cart_item->product != null) {
                array_push($cart_items,$cart_item);
            }
        }
        return view('cart')->with('cart_items',$cart_items);
    }

}
